<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>高性能不规则图片边框</title>
    <style>
        body { font-family: Arial, sans-serif; margin: 20px; }
        .container { display: flex; gap: 20px; margin-bottom: 20px; }
        canvas { border: 1px solid #ccc; }
        .controls { margin: 20px 0; }
        button { padding: 10px 15px; margin: 5px; }
    </style>
</head>
<body>
<h1>高性能边框绘制方案</h1>

<div class="container">
    <div>
        <h3>原始图片</h3>
        <canvas id="originalCanvas" width="400" height="400"></canvas>
    </div>
    <div>
        <h3>优化边框</h3>
        <canvas id="resultCanvas" width="400" height="400"></canvas>
    </div>
</div>

<div class="controls">
    <button onclick="drawBorderFast()">快速绘制（推荐）</button>
    <button onclick="drawBorderPrecise()">精确绘制（较慢）</button>
    <button onclick="drawBorderOptimized()">平衡模式</button>
</div>

<div id="performance"></div>

<script>
    const originalCanvas = document.getElementById('originalCanvas');
    const resultCanvas = document.getElementById('resultCanvas');
    const originalCtx = originalCanvas.getContext('2d');
    const resultCtx = resultCanvas.getContext('2d');
    const performanceDiv = document.getElementById('performance');

    // 加载测试图片
    const img = new Image();
    img.onload = function() {
        drawOriginalImage();
    };
    img.src = './1.png';

    function drawOriginalImage() {
        const scale = Math.min(
            originalCanvas.width / img.width,
            originalCanvas.height / img.height
        );
        const width = img.width * scale;
        const height = img.height * scale;
        const x = (originalCanvas.width - width) / 2;
        const y = (originalCanvas.height - height) / 2;

        originalCtx.drawImage(img, x, y, width, height);
    }

    // 方案1：快速阴影方法（性能最佳）
    function drawBorderFast() {
        const startTime = performance.now();

        resultCtx.clearRect(0, 0, resultCanvas.width, resultCanvas.height);

        const scale = Math.min(
            resultCanvas.width / img.width,
            resultCanvas.height / img.height
        );
        const width = img.width * scale;
        const height = img.height * scale;
        const x = (resultCanvas.width - width) / 2;
        const y = (resultCanvas.height - height) / 2;

        resultCtx.save();

        // 绘制阴影作为边框
        resultCtx.shadowColor = '#ff5722';
        resultCtx.shadowBlur = 15;
        resultCtx.drawImage(img, x, y, width, height);

        // 覆盖原始图片
        resultCtx.shadowBlur = 0;
        resultCtx.globalCompositeOperation = 'source-in';
        resultCtx.drawImage(img, x, y, width, height);

        resultCtx.restore();

        const endTime = performance.now();
        performanceDiv.innerHTML = `快速方法耗时: ${(endTime - startTime).toFixed(2)}ms`;
    }

    // 方案2：精确边缘检测（性能较差）
    function drawBorderPrecise() {
        const startTime = performance.now();

        resultCtx.clearRect(0, 0, resultCanvas.width, resultCanvas.height);

        const scale = Math.min(
            resultCanvas.width / img.width,
            resultCanvas.height / img.height
        );
        const width = img.width * scale;
        const height = img.height * scale;
        const x = (resultCanvas.width - width) / 2;
        const y = (resultCanvas.height - height) / 2;

        // 绘制原始图片
        resultCtx.drawImage(img, x, y, width, height);

        // 获取图片数据
        const imageData = resultCtx.getImageData(0, 0, resultCanvas.width, resultCanvas.height);
        const data = imageData.data;

        const edgePixels = [];

        // 精确边缘检测
        for (let y = 0; y < resultCanvas.height; y++) {
            for (let x = 0; x < resultCanvas.width; x++) {
                const index = (y * resultCanvas.width + x) * 4;
                const alpha = data[index + 3];

                if (alpha > 0) {
                    let isEdge = false;

                    // 检查周围像素
                    for (let dy = -1; dy <= 1; dy++) {
                        for (let dx = -1; dx <= 1; dx++) {
                            if (dx === 0 && dy === 0) continue;

                            const nx = x + dx;
                            const ny = y + dy;

                            if (nx >= 0 && nx < resultCanvas.width && ny >= 0 && ny < resultCanvas.height) {
                                const nIndex = (ny * resultCanvas.width + nx) * 4;
                                if (data[nIndex + 3] === 0) {
                                    isEdge = true;
                                    break;
                                }
                            }
                        }
                        if (isEdge) break;
                    }

                    if (isEdge) edgePixels.push({x, y});
                }
            }
        }

        // 绘制边框
        resultCtx.fillStyle = '#ff5722';
        edgePixels.forEach(pixel => {
            resultCtx.fillRect(pixel.x - 1, pixel.y - 1, 3, 3);
        });

        const endTime = performance.now();
        performanceDiv.innerHTML = `精确方法耗时: ${(endTime - startTime).toFixed(2)}ms - 检测到 ${edgePixels.length} 个边缘像素`;
    }

    // 方案3：平衡模式
    function drawBorderOptimized() {
        const startTime = performance.now();

        resultCtx.clearRect(0, 0, resultCanvas.width, resultCanvas.height);

        const scale = Math.min(
            resultCanvas.width / img.width,
            resultCanvas.height / img.height
        );
        const width = img.width * scale;
        const height = img.height * scale;
        const x = (resultCanvas.width - width) / 2;
        const y = (resultCanvas.height - height) / 2;

        resultCtx.drawImage(img, x, y, width, height);

        const imageData = resultCtx.getImageData(0, 0, resultCanvas.width, resultCanvas.height);
        const data = imageData.data;

        const edgePixels = [];
        const sampleRate = 2; // 每2个像素采样一次

        // 优化版边缘检测
        for (let y = 0; y < resultCanvas.height; y += sampleRate) {
            for (let x = 0; x < resultCanvas.width; x += sampleRate) {
                const index = (y * resultCanvas.width + x) * 4;
                const alpha = data[index + 3];

                if (alpha > 0) {
                    let isEdge = false;

                    // 只检查4个主要方向
                    const directions = [[0, -1], [0, 1], [-1, 0], [1, 0]];
                    for (const [dx, dy] of directions) {
                        const nx = x + dx * sampleRate;
                        const ny = y + dy * sampleRate;

                        if (nx >= 0 && nx < resultCanvas.width && ny >= 0 && ny < resultCanvas.height) {
                            const nIndex = (ny * resultCanvas.width + nx) * 4;
                            if (data[nIndex + 3] === 0) {
                                isEdge = true;
                                break;
                            }
                        } else {
                            isEdge = true;
                            break;
                        }
                    }

                    if (isEdge) edgePixels.push({x, y});
                }
            }
        }

        // 绘制边框
        resultCtx.fillStyle = '#ff5722';
        edgePixels.forEach(pixel => {
            resultCtx.fillRect(pixel.x - 2, pixel.y - 2, 4, 4);
        });

        const endTime = performance.now();
        performanceDiv.innerHTML = `平衡方法耗时: ${(endTime - startTime).toFixed(2)}ms - 检测到 ${edgePixels.length} 个边缘像素`;
    }
</script>
</body>
</html>
